package com.zha.boss.job.jobTask;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.xxl.job.core.handler.annotation.XxlJob;

import com.zha.boss.client.mail.Attachment;
import com.zha.boss.client.mail.MailClient;
import com.zha.boss.client.mail.MailProperties;
import com.zha.boss.dao.mapper.TradeOrderMapper;
import com.zha.boss.dao.mapper.UserInfoMapper;
import com.zha.boss.dao.result.TradeOrderBill;
import com.zha.boss.dao.result.UserInfoBill;
import com.zha.boss.job.excel.DateBillHeader;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author: zha
 * @CreateTime: 2024年09月27日 16:43
 */
@Component
public class TaskManger {
    /**
     * @XxJob 注解，用于声明一个定时任务，value属性为任务的唯一标识(说明定时任务方法的)
     * value : 定时任务唯一标识，任务方法名即为value值(定时任务的唯一名称)
     */
    @XxlJob(value = "testTask")
    public void testTake(){
        System.out.println("定时任务执行了"+new Date());
    }
    @Value("${bill.path}")
    private String dateBillPath;
    @Resource
    private MailClient mailClient;
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Resource
    private TradeOrderMapper tradeOrderMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    /**
     * 生成每日对账单
     */
    @XxlJob(value = "generateDayBill")
    public void generateDayBill(){
        Date current = new Date();
        Date yesterday = DateUtil.offsetDay(current, -1);
        DateTime beginDate = DateUtil.truncate(yesterday, DateField.DAY_OF_MONTH);
        DateTime endDate = DateUtil.truncate(current, DateField.DAY_OF_MONTH);
        // 1. 查询有支付成功记录的 user_no
        List<String> userNoList = tradeOrderMapper.selectUserNoListByBill(beginDate, endDate);
        // 2. 对每个userNo生成自己的对账单
        // 文件夹名称
        String dateFormat = new SimpleDateFormat("yyyyMMdd").format(yesterday);
        // 生成文件夹的路径
        Path path = Path.of(dateBillPath, dateFormat);
        try {
            if (!Files.exists(path)) { // path路径不存在则创建这个路径
               Files.createDirectories(path);
            }
        } catch (Exception e) {
           e.printStackTrace();
           return;
        }
        for (String userNo : userNoList) {
             threadPoolExecutor.execute(() -> {
                 List<TradeOrderBill> tradeOrderList = tradeOrderMapper.selectBillByUserNo(userNo, beginDate, endDate);
                 // 将list保存到excel文件  文件名称: userNo_yyyyMMdd.xlsx
                 String fileName = userNo + "_" + dateFormat + ".xlsx";
                 File file = Path.of(dateBillPath, dateFormat, fileName).toFile();  // 根据路径,获取一个文件的路径
                 EasyExcel.write(file, DateBillHeader.class)
                         .sheet("对账单")
                         .doWrite(tradeOrderList);
             });
        }
    }
    /**
     * 发送对账单的邮件
     */
    @XxlJob(value = "sendDayBillMail")
    public void sendDayBillMail(){
        Date current = new Date();
        Date yesterday = DateUtil.offsetDay(current, -1);
        DateTime beginDate = DateUtil.truncate(yesterday, DateField.DAY_OF_MONTH);
        DateTime endDate = DateUtil.truncate(current, DateField.DAY_OF_MONTH);
        // 查询有 账单的 用户和邮箱
        List<UserInfoBill> userInfoBillList = userInfoMapper.selectEmailByBill(beginDate,endDate);
        String dateFormat = new SimpleDateFormat("yyyyMMdd").format(yesterday);
        // 发送邮件
        for (UserInfoBill userInfoBill : userInfoBillList) {
            String fileName = userInfoBill.getUserNo() + "_" + dateFormat + ".xlsx";
            Path path = Path.of(dateBillPath, dateFormat, fileName);
            File file = path.toFile();
            if (!Files.exists(path)){
                continue;
            }
            MailProperties prop = new MailProperties();
            prop.setFrom("zhazhac@yeah.net");
            prop.setTo(new String[]{userInfoBill.getUserEmail()});
            prop.setSubject("每日对账单");
            prop.setText("每日对账单文件");
            Attachment attachment = new Attachment();
            attachment.setName("对账单附件");
            attachment.setFile(file);
            prop.setAttachments(List.of(attachment));
            mailClient.sendAttachmentsMail(prop);
        }
    }
}
